package com.javatian.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javatian.dao.OrderGoodsRelDao;
import com.javatian.dao.OrderInfoDao;
import com.javatian.entity.*;
import com.javatian.service.*;
import exception.CustomException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单信息对外提供的服务实现类
 */
@Service("orderInfoService")
public class OrderInfoServiceImpl implements OrderInfoService {

    @Resource
    private OrderInfoDao orderInfoDao;

    @Resource
    private AdminInfoService adminInfoService;

    @Resource
    private WorkerInfoService workerInfoService;

    @Resource
    private UserInfoService userInfoService;
    
    @Resource
    private GoodsInfoService goodsInfoService;

    @Resource
    private OrderGoodsRelDao orderGoodsRelDao;

    @Resource
    private CartInfoService cartInfoService;


    /**
     * 下单
     */
    @Override
    @Transactional
    public OrderInfo add(OrderInfo info) {
        Long userId = info.getUserId();
        Integer level = info.getLevel();
        Account userInfo = getUserInfo(userId, level);
        List<GoodsInfo> goodsList = info.getGoodsList();
        //创建一个订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setLevel(level);
        orderInfo.setStatus("待付款");
        orderInfo.setLinkAddress(userInfo.getAddress());
        orderInfo.setLinkMan(userInfo.getNickName());
        orderInfo.setLinkPhone(userInfo.getPhone());
        orderInfo.setCreateTime(DateUtil.formatDateTime(new Date()));
        //订单号：用户id+当前的年月日时分+4位流水号
        String orderId = userId+DateUtil.format(new Date(),"yyyyMMddHHmm")+ RandomUtil.randomNumbers(4);
        orderInfo.setOrderId(orderId);
        //生成订单
        orderInfoDao.insertSelective(orderInfo);
        
        double totalPrice = 0;
        for (GoodsInfo orderGoodsVO:goodsList){
            Long goodsId = orderGoodsVO.getId();
            //查询商品信息
            GoodsInfo goodsDetail = goodsInfoService.findById(goodsId);
            if (goodsDetail!=null){
                Integer orderCount = orderGoodsVO.getCount() == null ? 0 : orderGoodsVO.getCount();//要购买的数量
                Integer goodsCount = goodsDetail.getCount() == null ? 0:goodsDetail.getCount();    //当前库存
                //扣库存
                if (orderCount <= goodsCount){
                    goodsDetail.setCount(goodsCount - orderCount);
                    int sales = goodsDetail.getSales() == null ? 0 :goodsDetail.getSales();
                    goodsDetail.setSales(sales + orderCount);
                    goodsInfoService.update(goodsDetail);

                    //建立关系
                    OrderGoodsRel orderGoodsRel = new OrderGoodsRel();
                    orderGoodsRel.setCount(orderCount);
                    orderGoodsRel.setGoodsId(goodsId);
                    orderGoodsRel.setOrderId(orderInfo.getId());
                    orderGoodsRelDao.insertSelective(orderGoodsRel);

                    totalPrice+=goodsDetail.getPrice()*goodsDetail.getDiscount()*orderCount;
                }
            }

        }
        orderInfo.setTotalPrice(totalPrice);
        //更新订单信息
        orderInfoDao.updateByPrimaryKeySelective(orderInfo);

        //下单完后，清空购物车
        cartInfoService.empty(userId,level);
        return info;
    }

    /**
     * 删除一条记录
     *
     * @param id
     */
    @Override
    @Transactional
    public void delete(Long id) {
        orderInfoDao.deleteById(id);
        orderGoodsRelDao.deleteByOrderId(id);


    }

    /**
     * 修改订单状态
     *
     * @param id 主键id
     * @param status 要修改成的状态
     */
    @Override
    @Transactional
    public void changeStatus(Long id, String status) {
        OrderInfo order = orderInfoDao.findById(id);
        Long userId = order.getUserId();
        Integer level = order.getLevel();
        if (level == 1){
            AdminInfo user = adminInfoService.findById(userId);
            if (status.equals("待发货")){
                Double account = user.getAccount();
                Double totalPrice = order.getTotalPrice();
                if (account<totalPrice){
                    throw new CustomException("-1","账户余额不足");
                }
                user.setAccount(user.getAccount() - order.getTotalPrice());
                adminInfoService.update(user);
            }
            if (status.equals("已退款")||status.equals("已退货")){
                user.setAccount(user.getAccount() + order.getTotalPrice());
                adminInfoService.update(user);
            }
            orderInfoDao.updateStatus(id,status);

        }
        if (level == 2){
            WorkerInfo user = workerInfoService.findById(userId);
            if (status.equals("待发货")){
                Double account = user.getAccount();
                Double totalPrice = order.getTotalPrice();
                if (account<totalPrice){
                    throw new CustomException("-1","账户余额不足");
                }
                user.setAccount(user.getAccount() - order.getTotalPrice());
                workerInfoService.update(user);
            }
            if (status.equals("已退款")||status.equals("已退货")){
                user.setAccount(user.getAccount() + order.getTotalPrice());
                workerInfoService.update(user);
            }
            orderInfoDao.updateStatus(id,status);

        }
        if (level == 3){
            UserInfo user = userInfoService.findById(userId);
            if (status.equals("待发货")){
                Double account = user.getAccount();
                Double totalPrice = order.getTotalPrice();
                if (account<totalPrice){
                    throw new CustomException("-1","账户余额不足");
                }
                user.setAccount(user.getAccount() - order.getTotalPrice());
                userInfoService.update(user);
            }
            if (status.equals("已退款")||status.equals("已退货")){
                user.setAccount(user.getAccount() + order.getTotalPrice());
                userInfoService.update(user);
            }
            orderInfoDao.updateStatus(id,status);

        }

    }

    /**
     * 根据主键查询一条记录
     *
     * @param id
     */
    @Override
    public OrderInfo findById(Long id) {
        return null;
    }

    /**
     * 查询某个用户的所有订单
     *
     * @param user
     * @param level
     */
    @Override
    public List<OrderInfo> findAll(Long user, Integer level) {
        return null;
    }

    /**
     * 根据条件分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param user
     */
    @Override
    public PageInfo<OrderInfo> findEndPage(Integer pageNum, Integer pageSize, Account user) {
        if (user == null){
            throw new CustomException("1001","session已失效，请重新登录");
        }
        Integer level = user.getLevel();
        Long userId = user.getId();
        PageHelper.startPage(pageNum,pageSize);
        List<OrderInfo> orderInfos = new ArrayList<>();
        if (level == 1){
            orderInfos = orderInfoDao.selectAll();
        }else if (userId!= null){
            orderInfos = orderInfoDao.findByEndUserId(userId,level,null);
        }
        for (OrderInfo orderInfo:orderInfos) {
            packOrder(orderInfo);
        }
        return PageInfo.of(orderInfos);
    }

    @Override
    public PageInfo<OrderInfo> findFrontPage(Integer pageNum, Integer pageSize, Long userId, Integer level) {
        PageHelper.startPage(pageNum,pageSize);
        List<OrderInfo> orderInfos = new ArrayList<>();
        if (userId!=null){
            orderInfos = orderInfoDao.findByUserId(userId,level);
        }
        for (OrderInfo orderInfo:orderInfos) {
            packOrder(orderInfo);
        }
        return PageInfo.of(orderInfos);
    }

    @Override
    public Double totalPrice() {
        return orderInfoDao.totalPrice();
    }

    @Override
    public List<Map<String, Object>> getTypePrice() {
        return orderInfoDao.getTypePrice();
    }

    @Override
    public List<Map<String, Object>> getTypeCount() {
        return orderInfoDao.getTypeCount();
    }

    /**
     * 包装订单的用户和商品信息
     */

    private void packOrder(OrderInfo orderInfo){
        orderInfo.setUserInfo(getUserInfo(orderInfo.getUserId(),orderInfo.getLevel()));
        Long orderId = orderInfo.getId();
        List<OrderGoodsRel> rels = orderGoodsRelDao.findByOrderId(orderId);
        List<GoodsInfo> goodsList = CollUtil.newArrayList();
        for (OrderGoodsRel rel : rels){
            GoodsInfo goodsInfo = goodsInfoService.findById(rel.getGoodsId());
            if (goodsInfo!=null){
                //注意这里的count是用户加入商品的数量，而不是商品库存
                goodsInfo.setCount(rel.getCount());
                goodsList.add(goodsInfo);
            }
        }
        orderInfo.setGoodsList(goodsList);
    }

    /**
     * 根据用户ID和用户等级获取用户信息
     */
    private Account getUserInfo(Long userId,Integer level){
        Account account = new Account();
        if (level == 1){
            account = adminInfoService.findById(userId);
        }else if (level == 2){
            account = workerInfoService.findById(userId);
        }else if (level == 3){
            account = userInfoService.findById(userId);
        }
        return account;
    }
}
